package test;


import java.io.*;

public class test {

    static int[][] original=new int[11][11];

    public static void main(String[] args) {

        original[1][2]=1;//落子的数据
        original[2][3]=2;

        int[][] sparse=originalToSparse(original);
        print(sparse);
        print(sparseToOriginal());

    }
    public static void print(int[][] array){
        for(int[] a:array){
            for (int j : a) {
                System.out.print(j + "\t");
            }
            System.out.println();
        }
    }

    public static int[][] originalToSparse(int[][] original){//原数组转稀疏数组


        int sum =0;
        for (int[] array : original) //寻找有效数据的个数
            for (int j = 0; j < original.length; j++)
                if (array[j] != 0)
                    sum++;

        int[][] sparse=new int[sum+1][3];

        sparse[0][0]=original.length;
        sparse[0][1]=original.length;
        sparse[0][2]=sum;

        sum=1;

        for (int i=0;i<original.length;i++)//寻找有效数据的个数
            for (int j = 0; j < original.length; j++)
                if (original[i][j] != 0)
                {
                    sparse[sum][0]=i;
                    sparse[sum][1]=j;
                    sparse[sum][2]=original[i][j];
                    sum++;
                }

        try {//将稀疏数组保存至文件中
           ObjectOutputStream file=new ObjectOutputStream(new FileOutputStream("src\\test\\map.dat"));
           file.writeObject(sparse);
           file.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sparse;
    }

    public static int[][] sparseToOriginal(){//稀疏数组转原数组

        int[][] sparse=null;
        try {//读取文件中的数据转化数组
            ObjectInputStream file=new ObjectInputStream(new FileInputStream("src\\test\\map.dat"));
            sparse=(int[][])file.readObject();
            file.close();

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        int[][] original=new int[sparse[0][0]][sparse[0][1]];

        for(int i=1;i<=sparse[0][2];i++){
            original[sparse[i][0]][sparse[i][1]]=sparse[i][2];
        }

        return original;
    }

}
